import React, {Component, PropTypes} from 'react';
import {message} from 'antd';
import styles from './Main.less';
import {auth} from "../../services/authServer";
import {userInfo} from "../../services/authServer";

import cookie from 'js-cookie';
import {userCheck} from "../../services/authServer";


function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null)return unescape(r[2]);
  return null;
}

class CallbackMainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentWillMount() {
    var code = GetQueryString("code");
    if (code) {
      auth(code).then(function (res) {
        if (res.status == 200) {
          return res.json();
        } else {
        }
      }).then(function (data) {
        userInfo(data.access_token).then(function (json) {
          const user_id = json.message.user_id;
          const sarr = user_id.split(",");
          var cn = '';
          for (var s in sarr) {
            var str = sarr[s];
            var start = str.indexOf("cn=")
            if (start >= 0) {
              cn = str.substring(start + 3, str.length);
            }
          }

          userCheck(cn).then(function (res) {
            if (res.status == 200) {
              // cookie有效时间设置为30分钟
              var expires = new Date(new Date().getTime() + 30 * 60 * 1000);
              cookie.set('username', cn, { expires: expires });
              window.location.href = '/';
            } else {
              window.location.href = '/login';
            }
          }.bind(this));
        })
      }.bind(this));
    }
  }

  componentWillUnmount() {
  }

  render() {
    return (
      <div className={styles.login_center}>

      </div>
    );
  }
}

export default CallbackMainContainer;
